import 'dart:async';

import 'package:core_package/ui/widget/my_asset_image.dart';
import 'package:flutter/material.dart';
import 'package:core_package/core_package.dart';
import 'package:flutter_app_unionad/core/configuration.dart';
import 'package:flutter_app_unionad/model/task_item_model.dart';
import 'package:flutter_app_unionad/request/promotion_request.dart';
import 'package:flutter_app_unionad/ui/basice/my_button.dart';
import 'package:flutter_app_unionad/ui/promotion/delegate/account_amount_delegate.dart';
import 'package:flutter_app_unionad/ui/promotion/share_page.dart';
import 'package:flutter_app_unionad/ui/promotion/widget/take_list_item_widget.dart';
import 'package:flutter_unionad/flutter_unionad.dart' as FlutterUnionad;

class TaskCenterWidget extends StatefulWidget {
  final AccountAmountDelegate? delegate;

  const TaskCenterWidget({Key? key, this.delegate}) : super(key: key);

  @override
  _TaskCenterWidgetState createState() => _TaskCenterWidgetState();
}

class _TaskCenterWidgetState extends State<TaskCenterWidget> with AutomaticKeepAliveClientMixin {
  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
  List<TaskItemModel> dataSource = [];
  StreamSubscription? _adViewStream;

  TaskItemModel? model;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getData();

    _adViewStream = FlutterUnionad.FlutterUnionadStream.initAdStream(
      flutterUnionadFullVideoCallBack: FlutterUnionad.FlutterUnionadFullVideoCallBack(
        onShow: () {
          print("全屏广告显示");
        },
        onSkip: () {
          print("全屏广告跳过");
        },
        onClick: () {
          print("全屏广告点击");
        },
        onFinish: () {
          print("全屏广告结束");
        },
        onFail: (error) {
          ShowToastWidget.showToast(msg: '播放错误');
          print("全屏广告错误 $error");
        },
        onClose: () {
          print("全屏广告关闭");
          saveTask(model!);
        },
      ),
      //激励广告
      flutterUnionadRewardAdCallBack: FlutterUnionad.FlutterUnionadRewardAdCallBack(
        onShow: () {
          print("激励广告显示");
        },
        onClick: () {
          print("激励广告点击");
        },
        onFail: (error) {
          ProgressDialog.dismiss(context);
          ShowToastWidget.showToast(msg: '加载失败');
          print("激励广告失败 $error");
        },
        onClose: () {
          print("激励广告关闭");
        },
        onSkip: () {
          print("激励广告跳过");
        },
        onReady: () async {
          print("激励广告预加载准备就绪");
          ProgressDialog.dismiss(context);
          await FlutterUnionad.FlutterUnionad.showRewardVideoAd();
        },
        onUnReady: () {
          print("激励广告预加载未准备就绪");
          ProgressDialog.dismiss(context);

          ShowToastWidget.showToast(msg: '加载失败');
        },
        onVerify: (rewardVerify, rewardAmount, rewardName, errorCode, error) {
          print("激励广告奖励  验证结果=$rewardVerify 奖励=$rewardAmount  奖励名称$rewardName 错误吗=$errorCode 错误$error");
          saveTask(model!);
        },
      ),
      // 新模板渲染插屏广告回调
      flutterUnionadNewInteractionCallBack: FlutterUnionad.FlutterUnionadNewInteractionCallBack(
        onShow: () {
          print("新模板渲染插屏广告显示");
        },
        onSkip: () {
          print("新模板渲染插屏广告跳过");
        },
        onClick: () {
          print("新模板渲染插屏广告点击");
        },
        onFinish: () {
          print("新模板渲染插屏广告结束");
          saveTask(model!);
        },
        onFail: (error) {
          ProgressDialog.dismiss(context);
          ShowToastWidget.showToast(msg: '加载失败');
          print("新模板渲染插屏广告错误 $error");
        },
        onClose: () {
          print("新模板渲染插屏广告关闭");
        },
        onReady: () async {
          print("新模板渲染插屏广告预加载准备就绪");
          ProgressDialog.dismiss(context);

          //显示新模板渲染插屏
          await FlutterUnionad.FlutterUnionad.showFullScreenVideoAdInteraction();
        },
        onUnReady: () {
          ProgressDialog.dismiss(context);
          ShowToastWidget.showToast(msg: '加载失败');

          print("新模板渲染插屏广告预加载未准备就绪");
        },
      ),
      //插屏广告回调
      // flutterUnionadInteractionCallBack: FlutterUnionad.FlutterUnionadInteractionCallBack(
      //   onShow: () {
      //     print("插屏广告展示");
      //   },
      //   onClose: () {
      //     print("插屏广告关闭");
      //   },
      //   onFail: (error) {
      //     print("插屏广告失败 $error");
      //   },
      //   onClick: () {
      //     print("插屏广告点击");
      //     saveTask(model!);
      //
      //   },
      //   onDislike: (message) {
      //     print("插屏广告不喜欢  $message");
      //   },
      // ),
    );
    // _adViewStream = FlutterUnionad.FlutterUnionad.adeventEvent.receiveBroadcastStream().listen((data) {
    //   print("广告结果 ${data[FlutterUnionad.adType]}");
    //   if (data[FlutterUnionad.adType] == FlutterUnionad.rewardAd) {
    //     print("激励广告结果----->  rewardVerify=${data[FlutterUnionad.rewardVerify]} "
    //         "rewardName=${data[FlutterUnionad.rewardName]} "
    //         "rewardAmount=${data[FlutterUnionad.rewardAmount]} ");
    //     saveTask(model);
    //   } else if (data[FlutterUnionad.adType] == FlutterUnionad.fullVideoAd) {
    //     switch (data[FlutterUnionad.fullVideoType]) {
    //       case FlutterUnionad.onAdShow:
    //         print("全屏广告显示");
    //         break;
    //       case FlutterUnionad.onAdVideoBarClick:
    //         print("全屏广告返回");
    //         break;
    //       case FlutterUnionad.onAdClose:
    //         print("全屏广告关闭");
    //
    //         break;
    //       case FlutterUnionad.onVideoComplete:
    //         print("全屏广告继续");
    //         break;
    //       case FlutterUnionad.onSkippedVideo:
    //         print("全屏广告跳过");
    //         break;
    //     }
    //   }
    // });
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    if (_adViewStream != null) {
      _adViewStream?.cancel();
    }
  }

  void getData() {
    PromotionRequest.getTakeList().then((value) {
      setState(() {
        dataSource = value ?? [];
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Container(
        padding: EdgeInsets.symmetric(
          horizontal: 30.px,
          vertical: 25.px,
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              "每日福利",
              style: TextStyle(
                color: MyColors.color_27_27_27,
                fontSize: MyFont.font14,
                fontWeight: MyFontWeight.bold,
              ),
            ),
            MySizeBox(height: 8),
          ]..addAll(buildListView()),
        ),
      ),
    );
  }

  List<Widget> buildListView() {
    return List.generate(dataSource.length, (index) {
      return Column(
        children: [
          SizedBox(
            height: 7.px,
          ),
          TaskListItemWidget(
            itemModel: dataSource[index],
            onTap: () {
              itemOnTap(dataSource[index].taskOperation!, dataSource[index]);
            },
          ),
        ],
      );
    });
  }

  void itemOnTap(int index, TaskItemModel itemModel) {
    print('任务被点击---开始任务');
    model = itemModel;
    if (model!.userTaskStatus == 1) {
      print('保存任务');
      saveTask(itemModel);
      return;
    }
    if (index == 301) {
      //看福利视频
      ProgressDialog.showProgress(context);
      FlutterUnionad.FlutterUnionad.loadFullScreenVideoAdInteraction(
        androidCodeId: "945133612",
        //android 全屏广告id 必填
        iosCodeId: "939476092",
        //ios 全屏广告id 必填
        supportDeepLink: true,
        orientation: FlutterUnionad.FlutterUnionadOrientation.VERTICAL,
        downloadType: FlutterUnionad.FlutterUnionadDownLoadType.DOWNLOAD_TYPE_POPUP,
      );
    } else if (index == 302) {
      // 看激励视频
      ProgressDialog.showProgress(context);
      FlutterUnionad.FlutterUnionad.loadRewardVideoAd(
        mIsExpress: true,
        //是否个性化 选填
        androidCodeId: "945133610",
        //Android 激励视频广告id  必填
        iosCodeId: "939476582",
        //ios 激励视频广告id  必填
        supportDeepLink: true,
        //是否支持 DeepLink 选填
        rewardName: "${itemModel.point}金币",
        //奖励名称 选填
        rewardAmount: itemModel.point!.toInt(),
        //奖励数量 选填
        userID: '${UserCacheUil.getInt(Configuration.userId)}',
        //  用户id 选填
        orientation: FlutterUnionad.FlutterUnionadOrientation.VERTICAL,
        //视屏方向 选填
        mediaExtra: null,
        expressViewWidth: SizeFill.screenWidth,
        expressViewHeight: SizeFill.screenHeight,
        //扩展参数 选填
        downloadType: FlutterUnionad.FlutterUnionadDownLoadType.DOWNLOAD_TYPE_POPUP,
      );
    } else if (index == 304) {
      //邀请好友赚金币
      NavigatorUtil.push(context, SharePage.routeName).then((value) {
        if (value != null && value) {
          saveTask(itemModel);
        }
      });
    } else if (index == 308) {
      //每日分享
      NavigatorUtil.push(context, SharePage.routeName).then((value) {
        print("object");
        if (value != null && value) {
          saveTask(itemModel);
        }
      });
    }
  }

  void saveTask(TaskItemModel itemModel) {
    ProgressDialog.showProgress(context);
    PromotionRequest.saveGameTake(itemModel: itemModel).then((value) {
      ProgressDialog.dismiss(context);
      if (value != null && itemModel.userTaskStatus == 1) {
        ShowToastWidget.showToast(msg: "领取成功");
        if (widget.delegate != null) {
          widget.delegate!.reloadAmountWithOpen(value);
        }
      }

      getData();
    });
  }
}
